package com.jiahe.video.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.jiahe.video.config.LoginUserConfig;
import com.jiahe.video.constant.ApiUrl;
import com.jiahe.video.context.AppContent;
import com.jiahe.video.model.ApiResult;
import com.jiahe.video.model.Camera;
import com.jiahe.video.model.TokenInfo;
import com.jiahe.video.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class ApiServiceImpl extends AbsCommonService implements ApiService {

    @Value("${spring.profiles.active}")
    private String ACTIVE;

    @Resource
    private LoginUserConfig loginUserConfig;

    /**
     * 获得用户token
     * @return token
     */
    private String getToken(){

        // 1.首先从App上下文中获取
        TokenInfo tokenInfo = AppContent.getAppContent().getTokenInfo();
        if (tokenInfo!=null && StrUtil.isNotBlank(tokenInfo.getToken())) {
            return tokenInfo.getToken();
        }

        // 2.从接口中获取，并存入App上下文中
        log.info("账户登录：{} , {}",loginUserConfig.getAccount(),"******");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("account", loginUserConfig.getAccount());
        paramMap.put("password", loginUserConfig.getPassword());
        String url = ApiUrl.LOGIN;
        String result = HttpRequest.post(url)
                .form(paramMap)
                .timeout(ApiUrl.TIME_OUT_MAX)
                .execute().body();
        log.info("请求接口 {} , 参数:{} , 返回:{}",url, JSONObject.toJSONString(paramMap),result);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        if (apiResult.isSuccess()) {
            log.info(apiResult.getMsg());
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(apiResult.getData()));
            JSONObject userInfoJsonObject = JSONObject.parseObject(jsonObject.getString("userinfo"));
            String token = userInfoJsonObject.getString("token");
            String nickname = userInfoJsonObject.getString("nickname");
            Long expireTime = userInfoJsonObject.getLong("expiretime");
            TokenInfo tokenInfoNew = new TokenInfo();
            tokenInfoNew.build(token,nickname,expireTime);
            AppContent.getAppContent().setTokenInfo(tokenInfoNew);
            return token;
        }
        log.error(apiResult.getMsg());
        return null;
    }

    @Override
    public void nicknameInit() {
        getToken();
    }

    @Override
    public List<Camera> getCameraList() {
        List<Camera> cameraList = new ArrayList<>();
        HashMap<String, Object> paramMap = new HashMap<>();
        String url = ApiUrl.CAMERA_LIST;
        String result = HttpRequest.post(url)
                .form(paramMap)
                .header("token", getToken())
                .timeout(ApiUrl.TIME_OUT_MAX)
                .execute().body();
        log.info("请求接口 {} , 参数:{} , 返回:{}",url,JSONObject.toJSONString(paramMap),result);
        System.out.println(result);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        if (apiResult.isSuccess()) {
            log.info(apiResult.getMsg());
            cameraList = JSONObject.parseArray(JSONObject.toJSONString(apiResult.getData()), Camera.class);
        }
        return cameraList;
    }

    @Override
    public void uploadImage(Camera camera, String localFilePath) {
        log.info("carmeId = {},文件上传1:{}",camera.getId(),localFilePath);
        String fileName = localFilePath.substring(localFilePath.lastIndexOf("/")+1, localFilePath.length());
        String qiniuFilePath = "uploads/" + DateUtil.format(new Date(), "YYYYMMdd") + "/" + camera.getId() + "/" + fileName;
        String fileUrl = uploadFile2QiNiu(localFilePath, qiniuFilePath);
        log.info("carmeId = {},文件上传2:{}",camera.getId(),fileUrl);

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("camera_id", camera.getId());
        paramMap.put("picture", fileUrl);
        paramMap.put("people", 0);
        String url = ApiUrl.UPLOAD_CAMERA_FILE;
        String result = HttpRequest.post(url)
                .form(paramMap)
                .header("token", getToken())
                .timeout(ApiUrl.TIME_OUT_MAX)
                .execute().body();
        log.info("请求接口 {} , 参数:{} , 返回:{}",url,JSONObject.toJSONString(paramMap),result);
        System.out.println(result);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        if (apiResult.isSuccess()) {
            log.info(apiResult.getMsg());
        } else {
            log.error(apiResult.getMsg());
        }

    }

    @Override
    public void changeLightStatus(String groupId, boolean lightStatus,String localFilePath) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("group_id", groupId);
        paramMap.put("type", lightStatus?1:0);
        String url = ApiUrl.TURN_OFF_OR_TURN_ON_THE_LIGHT;
        String message = StrUtil.format("组{} -> {}\n{}",groupId,lightStatus?"开灯":"关灯",localFilePath);
        sendWeComMessage(message);
        if (!"pro".equals(ACTIVE)) {
            return;
        }
        String result = HttpRequest.post(url)
                .form(paramMap)
                .header("token", getToken())
                .timeout(ApiUrl.TIME_OUT_MAX)
                .execute().body();
        log.info("请求接口 {} , 参数:{} , 返回:{}",url,JSONObject.toJSONString(paramMap),result);
        log.info(result);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        if (!apiResult.isSuccess()) {
            log.error(apiResult.getMsg());
        }
    }


    public static void main(String[] args) {

        String localFilePath = "C:/Boot/bg-BG/abc.png";
        String fileName = localFilePath.substring(localFilePath.lastIndexOf("/")+1, localFilePath.length());
        System.out.println(fileName);
    }
}
